﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace OutlookAddIn_Collaboratori
{
    public class FolderSattings
    {
        public string[,] collectionField;

        //Название листа SharePoint
        private string m_ListName;
        public string ListName
        {
            get { return m_ListName; }
            set { m_ListName = value; }
        }
        //Название папки в outlook
        private string m_nameFolder;
        public string NameFolder
        {
            get { return m_nameFolder; }
            set { m_nameFolder = value; }
        }

        //Класс сообщений
        private string m_MessageClass;
        public string MessageClass
        {
            get { return m_MessageClass; }
            set { m_MessageClass = value; }
        }

        //Url адресс листа на SharePoint
        private string m_Url;
        public string Url
        {
            get { return m_Url; }
            set { m_Url = value; }
        }

        //Тип корневой папки Outlook
        private string m_DefaultMessageClass;
        public string DefaultMessageClass
        {
            get { return m_DefaultMessageClass; }
            set { m_DefaultMessageClass = value; }
        }

        public FolderSattings() { }
    }


    public class AddinSattings//: Investafinance.Credential
    {
        public List<FolderSattings> Folders = new List<FolderSattings>();

        //логин 
        private string m_UserName = null;
        public string UserName
        {
            get { return m_UserName; }
            set 
            {
                if (m_UserName != null)
                {
                    m_UserName = value;
                    m_change = true;
                    OnEventUpdateCreditional(new EventUpdateCreditionalEventArgs(m_UserName,m_Password,m_Domian));
                }
                else
                {
                    m_UserName = value;
                }
            }
        }

        //домин
        private string m_Domian = null;
        public string Domian
        {
            get { return m_Domian; }
            set 
            {
                if (m_Domian != null)
                {
                    m_Domian = value;
                    m_change = true;
                    OnEventUpdateCreditional(new EventUpdateCreditionalEventArgs(m_UserName,m_Password,m_Domian));
                }
                else
                {
                    m_Domian = value;
                }
            }
        }

        //пароль
        private string m_Password = null;
        public string Password
        {
            get { return m_Password; }
            set 
            {
                if (m_Password != null)
                {
                    m_Password = value;
                    m_change = true;
                    OnEventUpdateCreditional(new EventUpdateCreditionalEventArgs(m_UserName,m_Password,m_Domian));
                }
                else
                {
                    m_Password = value;
                }
            }
        }

        //проверка на изменения
        private bool m_change = false;
        public bool Change
        {
            get { return m_change; }
        }

        //Конструктор
        public AddinSattings(string pathXML) 
        {
            path = pathXML;
            doc = LoadConfig(path);
            LoadAddinSattings(doc); 
        }
        private string path;
        private XmlDocument doc;

        //Диструктор
        //Необходимо внести изменения в файл конфигурации
        ~AddinSattings()
        {
            if (this.Change)
            {
                XmlNodeList nodeList = doc.SelectNodes("/Config/Connect");
                foreach (XmlAttribute atribut in nodeList.Item(0).Attributes)
                {
                    switch (atribut.Name)
                    {
                        case ("UserName"):
                            atribut.Value = this.UserName;
                            break;
                        case ("Domian"):
                            atribut.Value = this.Domian;
                            break;
                        case ("Password"):
                            atribut.Value = this.Password;
                            break;
                    }
                }
                
                doc.Save(path);
            }
        }

        //Загрузить нгастройки из файла
        private XmlDocument LoadConfig(string path)
        {
            XmlDocument doc = new XmlDocument();
            try
            {
                //загрузка из файла по пути path 
                doc.Load(path);
            }
            catch
            {
                //в случае отсутствия xml на path создаём пустую xml
                doc.LoadXml("<Config> <Connect UserName='' Domian ='' Password=''/> <Folders><Folder Name='' MessageClass='' Url='' ListName=''><Field NameSharePoint='' NameOutlook='' ColumnNameOutlook='' ColumnTypeOutlook=''/></Folder></Folders></Config>");
                this.m_change = true;
            }
            return doc;
        }

        //выгрузить настройки из XmlDocument в AddinSattings
        private bool LoadAddinSattings(XmlDocument doc)
        {
            XmlNodeList nodeList = doc.SelectNodes("/Config/Folders/Folder");
            bool IsFolderAttribute = false;
            //AddinSattings Container = new AddinSattings();

            try
            {
                foreach (XmlNode Node in nodeList)
                {
                    FolderSattings folderSattings = new FolderSattings();

                    foreach (XmlAttribute atribut in Node.Attributes)
                    {
                        //считаем начальные значения
                        switch (atribut.Name)
                        {
                            case ("Name"):
                                folderSattings.NameFolder = atribut.Value;
                                break;
                            case ("MessageClass"):
                                folderSattings.MessageClass = atribut.Value;
                                break;
                            case ("Url"):
                                folderSattings.Url = atribut.Value;
                                break;
                            case ("ListName"):
                                folderSattings.ListName = atribut.Value;
                                break;
                            case ("DefaultMessageClass"):
                                folderSattings.DefaultMessageClass = atribut.Value;
                                break;
                        }
                        IsFolderAttribute = true;
                    }

                    if (IsFolderAttribute)
                    {
                        XmlNodeList Fields = Node.ChildNodes;
                        if (Fields.Count > 0)
                        {
                            string[,] collectionField = new string[Fields.Count, 4];
                            int count = 0;
                            foreach (XmlNode Field in Fields)
                            {
                                foreach (XmlAttribute atribut in Field.Attributes)
                                {
                                    switch (atribut.Name)
                                    {
                                        case ("NameSharePoint"):
                                            collectionField[count, 0] = atribut.Value;
                                            break;
                                        case ("NameOutlook"):
                                            collectionField[count, 1] = atribut.Value;
                                            break;
                                        case ("ColumnNameOutlook"):
                                            collectionField[count, 2] = atribut.Value;
                                            break;
                                        case ("ColumnTypeOutlook"):
                                            collectionField[count, 3] = atribut.Value;
                                            break;
                                    }
                                }
                                count++;
                            }
                            folderSattings.collectionField = collectionField;

                        }
                    }

                    IsFolderAttribute = false;
                    this.Folders.Add(folderSattings);
                }


                nodeList = doc.SelectNodes("/Config/Connect");
                foreach (XmlAttribute atribut in nodeList.Item(0).Attributes)
                {
                    switch (atribut.Name)
                    {
                        case ("UserName"):
                            this.UserName = atribut.Value;
                            break;
                        case ("Domian"):
                            this.Domian = atribut.Value;
                            break;
                        case ("Password"):
                            this.Password = atribut.Value;
                            break;
                    }
                }
            }
            catch
            {
                System.Windows.Forms.MessageBox.Show("File configuration bad");
                return false;
            }
            return true;
        }

        public event EventHandler<EventUpdateCreditionalEventArgs> EventUpdateCreditional;
        protected virtual void OnEventUpdateCreditional(EventUpdateCreditionalEventArgs e)
        {
            EventHandler<EventUpdateCreditionalEventArgs> temp = EventUpdateCreditional;
            if (temp != null) temp(this, e);
        }
    }

    //Событие обновление поля
    public class EventUpdateCreditionalEventArgs : EventArgs
    {
        private readonly string m_name, m_password, m_domian;
        public EventUpdateCreditionalEventArgs(string name, string password, string domian)
        {
            m_name = name;
            m_password = password;
            m_domian = domian;
        }

        public string Name { get { return m_name; } }
        public string Password { get { return m_password; } }
        public string Domian { get { return m_domian; } }
    }
   

}
